package com.hmdp.service.impl;

import com.hmdp.config.RedissonConfig;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisGlobalIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisGlobalIdWorker redisGlobalIdWorker;

    @Autowired
    private VoucherOrderServiceImpl voucherOrderService;

    @Autowired
    private RedissonClient redissonClient;


    /*
    通过lua+redis判断用户是否具有下单资格，将有资格的订单信息写入阻塞队列
    */
    //加载lua脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //阻塞队列
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    /**
     * redis判断后将订单信息写入阻塞队列
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();

        //执行lua脚本，获取返回值
        Long result = redisTemplate.execute(
                SECKILL_SCRIPT,     //执行的脚本
                Collections.emptyList(),     //key列表
                voucherId.toString(), userId.toString()   //ARGV参数列表
        );

        //判断lua脚本返回值
        //不为0，无资格，1-库存不足，2-不能重复下单
        int r = result.intValue();
        if (r != 0)
            return Result.fail(r == 1? "库存不足" : "不能重复下单");

        //为0，有资格，获取订单信息，并保存到阻塞队列
        //获取订单信息（即订单id）
        Long orderId = redisGlobalIdWorker.nextId("order");
        //创建订单信息
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);    //订单id
        voucherOrder.setUserId(userId);     //用户id
        voucherOrder.setVoucherId(voucherId);   //代金券id
        //放入阻塞队列中
        orderTasks.add(voucherOrder);

        //返回订单id
        return Result.ok(orderId);
    }



    /*
    异步下单——基于阻塞队列
     */
    //线程池，用于异步下单
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    //线程任务
    private class VoucherOrderHandler implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    //获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    //创建订单
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                }
            }
        }
    }

    //让线程在类初始化后就开始读取阻塞队列内容，提交订单
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    //创建订单信息，写入数据库
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder){
        //一人一单
        //查询用户id
        Long userId = voucherOrder.getUserId();

        //根据id查询订单，判断订单是否已经存在
        int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        //count >= 1，说明已经买过，不能再购买
        if (count >= 1) {
            log.error("请勿重复购买！");
            return;
        }

        //库存充足，扣减库存
        boolean success = seckillVoucherService.
                update().setSql("stock = stock - 1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock", 0) //保证修改时获取的库存充足即可售卖
                .update();
        if (!success){
            log.error("库存不足！");
            return;
        }

        //将订单插入数据库中
        save(voucherOrder);
    }

    //创建订单信息，根据当前线程是否可以获取锁来判断是否创建数据库信息，安全层面考虑
    private void handleVoucherOrder(VoucherOrder voucherOrder){
        //通过redisson获取锁&释放锁
        //创建锁对象
        String keyName = "lock:" + "order:" + voucherOrder.getUserId();
        RLock lock = redissonClient.getLock(keyName);
        //尝试获取锁
        boolean isLock = lock.tryLock();

        //获取锁失败，返回错误信息
        if (!isLock) {
            log.error("不能重复下单！");
            return;
        }

        //获取锁成功，执行下单操作
        try {
            voucherOrderService.createVoucherOrder(voucherOrder);
        }finally {
            lock.unlock();
        }
    }




    /*@Override
    public Result seckillVoucher(Long voucherId) {
        //通过id查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);

        //判断秒杀是否开始
        //未开始，返回异常
        if (voucher.getBeginTime().isAfter(LocalDateTime.now()))
            return Result.fail("秒杀未开始！");

        //秒杀开始开始，判断秒杀是否结束
        //已结束，返回异常
        if (voucher.getEndTime().isBefore(LocalDateTime.now()))
            return Result.fail("秒杀已结束！");

        Long userId = UserHolder.getUser().getId();

        //尝试获取锁
        *//*String keyName = "order:" + userId;
        SimpleRedisLock redisLock = new SimpleRedisLock(redisTemplate, keyName);  //锁的key应与用户有关，而不应只与业务有关
        boolean lock = redisLock.tryLock(1200L);
*//*

        //通过redisson获取锁&释放锁
        //创建锁对象
        String keyName = "lock:" + "order:" + userId;
        RLock lock = redissonClient.getLock(keyName);
        //尝试获取锁
        boolean isLock = lock.tryLock();

        //获取锁失败，返回错误信息
        if (!isLock)
            return Result.fail("请勿重复下单！");

        //获取锁成功，执行下单操作
        try {
            return voucherOrderService.createVoucherOrder(voucherId);
        }finally {
            lock.unlock();
        }
    }*/


    /**
     * 成功生成订单
     * @param voucherId
     * @return
     */
    /*@Transactional
    public Result createVoucherOrder(Long voucherId){
        //查询库存信息
        //库存不足，返回异常
        Integer stock = seckillVoucherService.getById(voucherId).getStock(); //查询时获取的库存
        if (stock < 1)
            return Result.fail("库存不足！");

        //一人一单
        //查询用户id
        Long userId = UserHolder.getUser().getId();

        //根据id查询订单，判断订单是否已经存在
        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        //count >= 1，说明已经买过，不能再购买
        if (count >= 1)
            return Result.fail("只能购买一次！");

        //库存充足，扣减库存
        boolean success = seckillVoucherService.
                update().set("stock", stock - 1)
                .eq("voucher_id", voucherId)
                .gt("stock", 0) //保证修改时获取的库存充足即可售卖
                .update();
        if (!success)
            return Result.fail("库存不足！");

        //创建订单
        //创建订单对象
        VoucherOrder voucherOrder = new VoucherOrder();
        Long orderId = redisGlobalIdWorker.nextId("order");
        voucherOrder.setId(orderId);    //设置订单id
        voucherOrder.setUserId(userId);   //通过本地线程获取用户id
        voucherOrder.setVoucherId(voucherId);   //代金券id
        //将订单插入数据库中
        save(voucherOrder);

        //返回订单id
        return Result.ok(orderId);
    }*/
}
